<template>
  <div>
    <el-card style="margin-left: 10px;margin-top: 2px;height: 80px">
      <el-form :inline="true" :model="blogs" ref="form">
        <el-form-item>
          <el-input size="small" v-model="blogs.title" placeholder="请输入要查找的内容"/>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="searchInfo">查询</el-button>
          <el-button icon="el-icon-refresh" type="primary" @click="resetFrom('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-left: 10px;margin-top: 2px">
      <el-button icon="el-icon-delete" color="danger" type="primary" @click="deleteBatch">批量删除</el-button>
      <el-button icon="el-icon-circle-plus-outline" color="success" type="primary" @click="addBlogs">添加博客</el-button>
      <el-button icon="el-icon-upload2" type="primary"  @ @click="Import">导入数据</el-button>
      <el-button
        icon="el-icon-download"
        type="primary"
        @click="exportExcel"
        :loading="exportLoading"
      >
        导出数据
      </el-button>
    </el-card>

    <el-dialog :title="title" :visible.sync="openImport" :close-on-click-modal="false" width="30%"
               @closed="ImportClose">
      <el-upload
        class="upload-excel"
        ref="upload"
        action="/dev-api/importExcel"
        :on-success="handleImportSuccess"
        :before-upload="beforeImportUpload"
        :file-list="importFileList"
        :on-change="handleFileChange"
        :auto-upload="false"
        accept=".xlsx,.xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
      </el-upload>
      <div slot="footer">
        <el-button @click="openImport = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="tip" :visible.sync="openBlogs" :close-on-click-modal="false" width="30%"
               @closed="handleDialogClosed">
      <el-form ref="elForm" :model="blogsForm" size="medium" label-width="100px" :rules="rules"
               :validate-on-rule-change="false">
        <el-form-item label="博客标题" prop="title">
          <el-input v-model="blogsForm.title" placeholder="博客标题" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="博客图片" prop="fileName">
          <el-upload
            class="upload-demo"
            action="/dev-api/upload"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="true"
            :limit="1"
            list-type="picture"
          >
            <el-button icon="el-icon-upload" size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="博客内容" prop="content">
          <el-input v-model="blogsForm.content" placeholder="博客内容" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="博客状态" prop="status">
          <el-select v-model="blogsForm.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别名字" prop="categoryname">
          <el-input v-model="blogsForm.categoryname" placeholder="类别名字" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="博客标签" prop="tags">
          <el-input v-model="blogsForm.tags" placeholder="博客标签" clearable :style="{width: '100%'}"/>
        </el-form-item>
        <el-form-item label="浏览次数" prop="views">
          <el-input type="number" v-model="blogsForm.views" placeholder="浏览次数" clearable
                    :style="{width: '100%'}"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

    <el-card style="margin-left: 10px;margin-top: 2px">
      <el-table
        :data="BlogsInfo"
        style="width: 100%"
        ref="multipleTable"
        border
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column
          type="selection"
          width="55"
          reserve-selection
        />
        <el-table-column
          prop="id"
          label="序号"
        >
        </el-table-column>
        <el-table-column
          prop="title"
          label="博客标题"
        >
        </el-table-column>
        <el-table-column
          prop="content"
          label="博客内容"
        >
        </el-table-column>
        <el-table-column
          prop="blogimg"
          label="博客图片">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.blogimg"
              :src="getImageUrl(scope.row.blogimg)"
              :preview-src-list="[getImageUrl(scope.row.blogimg)]"
              style="width: 50px; height: 50px; cursor: pointer"
              fit="cover"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdat"
          label="创建时间"
          :formatter="formatDate">
        </el-table-column>
        <el-table-column
          prop="status"
          label="博客状态">
        </el-table-column>
        <el-table-column
          prop="categoryname"
          label="类别名字">
        </el-table-column>
        <el-table-column
          prop="tags"
          label="博客标签">
        </el-table-column>
        <el-table-column
          prop="views"
          label="浏览次数">
        </el-table-column>
        <el-table-column
          prop="yonghuid"
          label="作者ID">
        </el-table-column>
        <el-table-column
          prop="yonghuname"
          label="用户名字">
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.$index, scope.row)" type="text" size="small">编辑</el-button>
            <el-button type="text" size="small" @click="deleteBlogs(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="display:flex; align-items: center" class="block" align="center">
        <el-pagination
          @size-change="handleSizeChange"
          :page-sizes="[1, 2, 3]"
          @current-change="handleCurrentChange"
          :page-size="blogs.pageSize"
          :current-page="blogs.pageNum"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
        <el-input-number v-model="blogs.pageNum" :min="1" :max="Math.ceil(total / blogs.pageSize)" size="small" style="margin-right: 10px;"></el-input-number>
        <el-button size="small" type="primary" plain @click="toPage">跳转</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
import { addBlogs, deleteBatch, deleteBlogs, findAll, updateBlogs, upLoad } from '@/api/project/usercomment'
import axios from 'axios';

export default {
  name: "userComment",
  data() {
    return {
      exportLoading: false,
      hasFileSelected: false,
      importFileList: [], // Excel导入文件列表
      title: "导入Excel数据", // 修改对话框标题
      options: [{
        value: 'published',
        label: '发布'
      }, {
        value: 'draft',
        label: '草稿'
      }],
      rules: {
        title: [
          {required: true, message: '请输入博客标题', trigger: 'blur'}
        ],
        content: [
          {required: true, message: '请输入博客内容', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择博客状态', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (['published', 'draft'].includes(value)) {
                callback();
              } else {
                callback(new Error('请选择有效的状态'));
              }
            },
            trigger: 'change'
          }
        ],
        categoryname: [
          {required: true, message: '请输入类别名称', trigger: 'blur'}
        ],
        tags: [
          {required: true, message: '请输入博客标签', trigger: 'blur'}
        ]
      },
      fileList: [], // 用于显示已上传文件列表
      file: null,  // 存储上传成功的文件URL
      openBlogs: false,
      openImport: false,
      tip: "",
      blogsForm: {},
      total: 0,
      blogs: {
        title: null,
        pageSize: 3,
        pageNum: 1,
      },
      BlogsInfo: [],
      multipleSelection: []
    }
  },
  methods: {
    exportExcel() {
      this.$confirm('确认要导出当前数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.exportLoading = true;
        this.$message.info('正在生成Excel文件，请稍候...');

        // 使用axios直接请求下载，带上查询条件
        axios({
          url: '/dev-api/picture/download/excel',
          method: 'GET',
          params: {
            title: this.blogs.title // 传递当前搜索条件
          },
          responseType: 'blob',
        }).then(response => {
          // 从响应头获取文件名
          const contentDisposition = response.headers['content-disposition'];
          let fileName = 'blogs_export.xlsx';
          if (contentDisposition) {
            const match = contentDisposition.match(/filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?;?/i);
            if (match && match[1]) {
              fileName = decodeURIComponent(match[1]);
            }
          }

          // 创建下载链接
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.exportLoading = false;
          this.$message.success('导出成功');
        }).catch(error => {
          if (error.response && error.response.status === 403) {
            // 处理权限错误等特殊情况
            this.$message.error(error.response.data.message || '导出失败');
          } else if (error.message && error.message.includes('cancelled')) {
            // 用户取消导出
            this.exportLoading = false;
            this.$message.info('已取消导出');
          } else {
            // 其他错误
            this.exportLoading = false;
            this.$message.error('导出失败: ' + (error.message || '未知错误'));
            console.error(error);
          }
        });
      }).catch(() => {
        this.$message.info('已取消导出');
      });
    },

    handleDialogClosed() {
      // 清除表单验证状态
      if (this.$refs.elForm) {
        this.$refs.elForm.clearValidate();
      }
    },

    formatDate(row, column, cellValue) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    getImageUrl(filename) {
      if (!filename) return '';
      // 如果已经是完整URL则直接返回
      if (filename.startsWith('https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/')) return filename;
      // 否则拼接基础URL（根据你的实际后端配置调整）
      return `https://wanghao1234.oss-cn-hangzhou.aliyuncs.com/g8hms/${filename}`;
    },

    handleUploadSuccess(response, file, fileList) {
      if (response.code === 20000) {
        this.blogsForm.blogimg = response.data; // 保存文件名到表单
        this.fileList = fileList;
      } else {
        this.$message.error(response.message || '上传失败');
      }
    },

    handleRemove(file, fileList) {
      this.blogsForm.blogimg = null;
      this.fileList = fileList;
    },

    findAll() {
      findAll(this.blogs).then(res => {
        if (res.code === 20000) {
          this.BlogsInfo = res.data.list;
          this.total = res.data.total;
        } else {
          this.$message.error(ret.message || '获取数据失败');
        }
      }).catch(error => {
        this.$message.error('请求失败: ' + error.message);
        console.error(error);
      });
    },

    deleteBlogs(index, row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBlogs({ id: row.id }).then(res => {
          if (res.code === 20000) {
            this.$message.success('删除成功');
            this.findAll();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('请求失败: ' + error.message);
          console.error(error);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    searchInfo() {
      this.findAll();
    },

    resetFrom(formName) {
      this.$refs[formName].resetFields();
      this.blogs.title = null;
      this.findAll();
    },

    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条记录');
        return;
      }
      this.$confirm('此操作将永久删除[' + this.multipleSelection + '], 是否继续?', '删除记录!', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteBatch(this.multipleSelection);
      }).then(res => {
        if (res.code === 20000) {
          this.$message.success('删除成功');
          this.findAll();
          this.$refs.multipleTable.clearSelection();
        }
      }).catch(error => {
        this.$message.error('请求失败: ' + error.message);
        console.error(error);
      });
    },

    handleSubmit() {
      this.$refs.elForm.validate(valid => {
        if (!valid) {
          this.$message.error('请填写完整且正确的表单信息');
          return false;
        }
        // 调用原来的Blogs方法
        this.Blogs();
      });
    },

    Blogs() {
      if (this.tip === "新增博客") {
        addBlogs(this.blogsForm).then(res => {
          if (res.code === 20000) {
            this.$message.success('添加成功');
            this.openBlogs = false;
            this.findAll();
          } else {
            this.$message.error(res.message || '添加失败');
          }
        }).catch(error => {
          this.$message.error('请求失败: ' + error.message);
          console.error(error);
        });
      } else {
        updateBlogs(this.blogsForm).then(res => {
          if (res.code === 20000) {
            this.$message.success('修改成功');
            this.openBlogs = false;
            this.findAll();
          } else {
            this.$message.error(res.message || '修改失败');
          }
        }).catch(error => {
          this.$message.error('请求失败: ' + error.message);
          console.error(error);
        });
      }
    },

    beforeImportUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!');
      }
      return isExcel && isLt10M;
    },

    handleImportSuccess(response, file, fileList) {
      if (this.uploadLoading) {
        this.uploadLoading.close();
      }

      if (response.code === 20000) {
        this.$message.success('导入成功');
        this.findAll();
        this.openImport = false;
        this.importFileList = [];
      } else {
        this.$message.error(response.message || '导入失败');
      }
    },

    handleFileChange(file, fileList) {
      this.hasFileSelected = fileList.length > 0;
      this.importFileList = fileList;
    },

    // 修改submitImport方法
    submitImport() {
      if (!this.hasFileSelected || this.importFileList.length === 0) {
        this.$message.warning('请先选择Excel文件');
        return;
      }

      this.uploadLoading = this.$loading({
        lock: true,
        text: '数据上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.$refs.upload.submit();
    },

    ImportClose() {
      this.importFileList = []; // 清空文件列表
    },

    // 修改原来的Import方法
    Import() {
      this.title = "导入Excel数据";
      this.openImport = true;
    },

    addBlogs() {
      this.tip = "新增博客";
      this.openBlogs = true;
      this.blogsForm = {
        title: '',
        content: '',
        status: 'draft',
        categoryname: '',
        tags: '',
        views: 1,
        blogimg: null,
      };
      this.fileList = []; // 清空文件列表
    },

    handleClick(index, row) {
      this.tip = "编辑内容";
      this.blogsForm = JSON.parse(JSON.stringify(row));
      this.openBlogs = true;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id);
    },

    handleSizeChange(val) {
      this.blogs.pageSize = val;
      this.findAll();
    },

    handleCurrentChange(val) {
      this.blogs.pageNum = val;
      this.findAll();
    },

    toPage() {
      const pageNum = this.$refs.toPage.value;
      if (pageNum >= 1 && pageNum <= Math.ceil(this.total / this.blogs.pageSize)) {
        this.blogs.pageNum = pageNum;
        this.findAll();
      } else {
        this.$message.error('请输入有效的页码');
      }
    },

    close() {
      this.openBlogs = false;
    }
  },
  created() {
    this.findAll();
  }
}
</script>

